﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace ProgrammersCalculator.Convertor
{
    public class EncryptionConverter : IValueConverter
    {
    //    function doCrypt(isDecrypt) {
    //var shiftText = document.getElementById("Output").value;
    //if (!/^-?\d+$/.test(shiftText)) {
    //    alert("Shift is not an integer");
    //    return;
    //}
    //var key = parseInt(shiftText, 10);
    //if (key < 0 || key >= 26) {
    //    alert("Shift is out of range");
    //    return;
    //}
    //if (isDecrypt)
    //    key = (26 - key) % 26;
    //var textElem = document.getElementById("Input");
    //textElem.value = crypt(textElem.value, key);
//}

        private static string DoCrypt(string input,bool isDecrypt,int shift)
        {
            var key=shift;
            if (key < 0 || key > 26)
                return string.Empty;
            if (isDecrypt)
            {
                key = (26 - key) % 26;
            }
           return Crypt(input, key);
        }

        private static string Crypt(string input, int key)
        {
            var output = "";
            for (var i = 0; i < input.Length; i++)
            {
                var c = input[i];
                if (c >= 65 && c <= 90) output += (char)((c - 65 + key) % 26 + 65);  // Uppercase
                else if (c >= 97 && c <= 122) output += (char)((c - 97 + key) % 26 + 97);  // Lowercase
                else output += input[i];  // Copy
            }
            return output;
        }

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            
            int param = System.Convert.ToInt32(parameter);
            string input = value.ToString();
            return Crypt(input, param);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
